<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>电力消费数据分析</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
    <style>
        /* 大屏样式调整 */
        body {
            font-size: 1.2rem;
        }
        .card {
            margin-bottom: 2rem;
        }
        .card-header {
            font-size: 1.5rem;
        }
        .table th, .table td {
            font-size: 1.2rem;
        }

        /* 响应式设计 */
        @media (min-width: 1200px) {
            .container {
                max-width: 90%;
            }
        }

        /* 新增热力图容器样式 */
        #heatmap-container {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        body{zoom:100%}

        #relationshipChartContainer {
            display:flex;
            justify-content: center;
            align-items: center;
        }
        #load-comparison-container{
            display:flex;
            justify-content: center;
            align-items: center;
        }
        #weather-load-pie-chart-container{
            display:flex;
            justify-content: center;
            align-items: center;
        }
        #loadCurveContainer{
            display:flex;
            justify-content: center;
            align-items: center;
        }
        .form-select {
        width: 150px; /* 可以根据需要调整宽度 */
        font-align:center;
        }
        /* 预览模态框样式 */
        #previewModal .modal-dialog {
            max-width: 90%;
        }
        #previewModal .modal-body {
            max-height: 70vh;
            overflow-y: auto;
        }
        /* 上传区域样式 */
        .upload-container {
            background-color: #f8f9fa;
            padding: 1.5rem;
            border-radius: 0.5rem;
            border: 1px dashed #dee2e6;
            margin-bottom: 1.5rem;
        }
        /* 进度条动画 */
        .progress-bar-animated {
            animation: progress-bar-stripes 1s linear infinite;
        }
        @keyframes progress-bar-stripes {
            0% { background-position-x: 1rem; }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top">
        <div class="container">
            <a class="navbar-brand fw-bold" href="#">
                <i class="bi bi-lightning-charge me-2"></i>电力消耗分析与预测
            </a>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item"></li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="#data-analysis" id="dataAnalysisTab">
                            <i class="bi bi-graph-up me-1"></i>数据分析
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#data-forecast" id="dataForecastTab">
                            <i class="bi bi-magic me-1"></i>数据预测
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#history" id="historyTab">
                            <i class="bi bi-clock-history me-1"></i>历史记录
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-5 pt-4">
        <h1 class="text-left mb-4">电力消耗预测</h1>

        <!-- 上传区域 -->
        <div class="upload-container">
            <div class="d-flex flex-wrap gap-2 mb-3">
                <a href="{{ url_for('download_template') }}" class="btn btn-primary" download>
                    <i class="bi bi-download me-1"></i> 下载模板
                </a>

                <button class="btn btn-success" id="uploadBtn">
                    <i class="bi bi-upload me-1"></i> 上传文件
                </button>
                <input type="file" id="fileInput" accept=".xlsx" style="display:none;">

                <button class="btn btn-info" id="previewBtn" disabled>
                    <i class="bi bi-eye me-1"></i> 预览
                </button>

                <button type="button" class="btn btn-primary">分析数据</button>

            </div>

            <!-- 上传进度条 -->
            <div class="progress mb-3" style="height: 25px; display: none;" id="progressContainer">
                <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated"
                     role="progressbar" style="width: 0%">0%</div>
            </div>

            <!-- 文件信息 -->
            <div id="fileInfo" class="alert alert-info mb-0" style="display: none;"></div>
        </div>

        <!-- 添加pt-4给导航栏留出空间 -->
        <h1 class="text-left mb-4">电力消耗数据分析</h1>

        <div class="row">
            <div class="col-md-4 mb-4">
                <div class="card h-100">
                    <div class="card-header">
                        <h2>数据集基本统计</h2>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>属性</th>
                                        <th>最大值</th>
                                        <th>最小值</th>
                                        <th>均值</th>
                                        <th>标准差</th>
                                    </tr>
                                </thead>
                                <tbody id="stats-table-body">
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-8 mb-4">
                <div class="card h-100">
                    <div class="card-header">
                        <h3>相关性热力图</h3>
                    </div>
                    <div class="card-body" id="heatmap-container">
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6 mb-4">
                <div class="card h-100">
                    <div class="card-header">
                        <h3>节假日影响</h3>
                    </div>
                    <div class="card-body" id="load-comparison-container">
                    </div>
                </div>
            </div>

            <div class="col-md-6 mb-4">
                <div class="card h-100">
                    <div class="card-header">
                        <h3>相关性分析</h3>
                    </div>
                     <div class="card-body" id="weather-load-pie-chart-container">
                </div>
            </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 mb-4">
                <div class="card h-100">
                    <div class="card-header">
                        <h3>用电量与其他特征的关系</h3>
                    </div>
                    <div class="card-body">
                    <select id="featureSelect" class="form-select mb-3">
                        <option value="Max_Temperature">最高温度</option>
                        <option value="Min_Temperature">最低温度</option>
                        <option value="Avg_Temperature">平均温度</option>
                        <option value="Avg_Humidity">平均湿度</option>
                        <option value="Rainfall">降雨量</option>
                    </select>
                    <div id="relationshipChartContainer"></div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 mb-4">
                <div class="card h-100">
                    <div class="card-header">
                        <h3>时刻负荷趋势图</h3>
                    </div>
                    <div class="card-body" id="loadCurveContainer">
                </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 预览模态框 -->
    <div class="modal fade" id="previewModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="previewModalLabel">Excel文件预览</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="previewData">
                    <div class="text-center my-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p>正在加载预览数据...</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const uploadBtn = document.getElementById('uploadBtn');
            const fileInput = document.getElementById('fileInput');
            const previewBtn = document.getElementById('previewBtn');
            const progressContainer = document.getElementById('progressContainer');
            const progressBar = document.getElementById('progressBar');
            const fileInfo = document.getElementById('fileInfo');
            const previewModal = new bootstrap.Modal('#previewModal');
            let currentFile = null;

            // 点击上传按钮
            uploadBtn.addEventListener('click', function() {
                fileInput.click();
            });

            // 文件选择处理
            fileInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (!file) return;

                // 验证文件类型
                const fileExt = file.name.split('.').pop().toLowerCase();
                if (!['xlsx'].includes(fileExt)) {
                    showAlert('danger', '请选择.xlsx格式的文件');
                    return;
                }

                currentFile = file;

                previewBtn.disabled = true;

                // 显示文件信息
                fileInfo.style.display = 'block';
                fileInfo.innerHTML = `
                    <i class="bi bi-file-earmark-excel"></i>
                    已选择文件: <strong>${file.name}</strong> (${formatFileSize(file.size)})
                    <button class="btn btn-sm btn-outline-primary float-end" id="startUploadBtn">
                        <i class="bi bi-cloud-upload"></i> 开始上传
                    </button>
                `;

                // 开始上传按钮
                document.getElementById('startUploadBtn').addEventListener('click', function() {
                    uploadFile(file);
                });
            });

            // 预览按钮
            previewBtn.addEventListener('click', function() {
                if (!currentFile ||!currentFile.uploaded) return;
                console.log('当前文件信息:', currentFile);
                previewModal.show();
                loadPreviewData(currentFile.name,currentFile.stored_filename);
            });

            // 上传文件函数
            function uploadFile(file) {
                const formData = new FormData();
                formData.append('file', file);

                // 显示进度条
                progressContainer.style.display = 'block';
                progressBar.style.width = '0%';
                progressBar.textContent = '0%';
                progressBar.classList.remove('bg-success', 'bg-danger');
                fileInfo.classList.remove('alert-danger');
                fileInfo.classList.add('alert-info');
                const xhr = new XMLHttpRequest();

                // 进度事件
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        const percent = Math.round((e.loaded / e.total) * 100);
                        updateProgress(percent);

                        // 更新文件信息
                        fileInfo.innerHTML = `
                            <i class="bi bi-file-earmark-arrow-up"></i>
                            上传中: <strong>${file.name}</strong>
                            (${formatFileSize(e.loaded)}/${formatFileSize(e.total)})
                            ${percent}%
                        `;
                    }
                });

                xhr.addEventListener('load', function() {
                    if (xhr.status === 200) {
                        const response = JSON.parse(xhr.responseText);
                        updateProgress(100, '上传完成!', 'bg-success');
                        fileInfo.innerHTML = `
                            <i class="bi bi-check-circle-fill text-success"></i>
                            <strong>${file.name}</strong> 上传成功!
                            <button class="btn btn-sm btn-outline-danger float-end me-2" id="deleteFileBtn">
                                <i class="bi bi-x"></i>删除
                            </button>
                        `;

                        // 更新当前文件信息
                        currentFile = {
                            name: response.filename,
                            stored_filename: response.stored_filename,
                            size: response.size,
                            uploaded: true
                        };

                        previewBtn.disabled = false;

                        // 3秒后隐藏进度条
                        setTimeout(() => {
                            progressContainer.style.display = 'none';
                        }, 3000);

                        // 删除文件按钮
                        document.getElementById('deleteFileBtn').addEventListener('click', function() {
                            if (confirm('确定要删除这个文件吗？')) {
                                deleteFile(currentFile.name);
                            }
                        });
                    }
                    else if(xhr.status === 400){
                        const error = JSON.parse(xhr.responseText).error;
                        updateProgress(0, error, 'bg-danger');
                        showAlert('danger', `文件上传失败: ${error}`);
                    }
                    else if(xhr.status === 500) {
                        const error = JSON.parse(xhr.responseText).error || '文件处理失败';
                        updateProgress(0, '文件处理失败', 'bg-danger');
                        showAlert('danger', `文件处理失败: ${error}`);
                    }
                    else{
                        const error = JSON.parse(xhr.responseText).error || '文件未找到';
                        updateProgress(0, '文件处理失败', 'bg-danger');
                        showAlert('danger', `文件处理失败: ${error}`);
                    }
                });

                xhr.addEventListener('error', function() {
                    updateProgress(0, '网络错误', 'bg-danger');
                    showAlert('danger', '网络错误，上传中断');
                });

                xhr.open('POST', '/upload', true);
                xhr.send(formData);
            }

            // 删除文件函数
            function deleteFile(filename) {
                fetch(`/delete/${encodeURIComponent(filename)}`, {
                    method: 'DELETE'
                })
               .then(response => {
                    if (!response.ok) {
                        throw new Error(`删除失败，状态码: ${response.status}`);
                    }
                    return response.json();
                })
               .then(data => {
                    if (data.success) {
                        fileInfo.style.display = 'none';
                        previewBtn.disabled = true;
                        currentFile = null;
                        alert('删除成功');
                    } else {
                        throw new Error(data.message || '删除失败');
                    }
                })
               .catch(error => {
                    console.error('删除错误:', error);
                    alert('删除失败: ' + error.message);
                });
            }

            // 加载预览数据
            function loadPreviewData(filename,stored_filename) {
                const previewData = document.getElementById('previewData');
                previewData.innerHTML = `
                    <div class="text-center my-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p>正在加载预览数据...</p>
                    </div>
                `;
                // 检查请求 URL 和参数
            const url = `/preview?filename=${encodeURIComponent(filename)}&stored_filename=${encodeURIComponent(stored_filename)}`;
            console.log('请求 URL:', url);
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if ('error' in data) {
                        previewData.innerHTML = `
                            <div class="alert alert-danger">
                                <i class="bi bi-exclamation-triangle"></i>
                                ${data.error}
                            </div>
                        `;
                        return;
                    }

                    let tableHtml = '';
                    for (const [sheetName, sheetData] of Object.entries(data)) {
                        tableHtml += `
                            <h5>${sheetName}</h5>
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h6 class="mb-0">${sheetData.filename}</h6>
                                <small class="text-muted">共 ${sheetData.row_count} 行数据</small>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-sm table-bordered table-hover">
                                    <thead class="table-light">
                                        <tr>
                        `;

                                    // 表头
                                    sheetData.columns.forEach(column => {
                                        tableHtml += `<th>${column}</th>`;
                                    });

                                    tableHtml += `
                                                    </tr>
                                                </thead>
                                                <tbody>
                                    `;

                                    // 表格内容
                                    sheetData.content.forEach(row => {
                                        tableHtml += `<tr>`;
                                        sheetData.columns.forEach(column => {
                                            tableHtml += `<td>${row[column] || ''}</td>`;
                                        });
                                        tableHtml += `</tr>`;
                                    });

                                    tableHtml += `
                                                </tbody>
                                            </table>
                                            <div class="text-muted mt-2">
                                                显示前 ${sheetData.content.length} 行数据 (共 ${sheetData.row_count} 行)
                                            </div>
                                            <hr>
                                        </div>
                                    `;
                                }

                                previewData.innerHTML = tableHtml;
                            })
                           .catch(error => {
                                previewData.innerHTML = `
                                    <div class="alert alert-danger">
                                        <i class="bi bi-exclamation-triangle"></i>
                                        加载预览失败: ${error.message}
                                    </div>
                                `;
                            });
                    }

            // 辅助函数
            function updateProgress(percent, text = null, bgClass = null) {
                progressBar.style.width = percent + '%';
                progressBar.textContent = text || percent + '%';
                if (bgClass) {
                    progressBar.classList.add(bgClass);
                }
            }

            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }

            function showAlert(type, message) {
                fileInfo.style.display = 'block';
                fileInfo.className = `alert alert-${type}`;
                fileInfo.innerHTML = message;
            }
        });
        document.getElementById('dataAnalysisTab').addEventListener('click', function() {
            window.location.href ="{{ url_for('data_analysis') }}";
            console.log('数据分析标签被点击');
        });

        document.getElementById('dataForecastTab').addEventListener('click', function() {
            window.location.href = "{{ url_for('data_yuce') }}";
            console.log('数据预测标签被点击');
        });

        document.getElementById('historyTab').addEventListener('click', function() {
             window.location.href = "{{ url_for('data_history') }}";
            console.log('历史记录标签被点击');
        });
        document.addEventListener('DOMContentLoaded', function() {
            const selectedFeature = 'Max_Temperature';
            fetch(`/get_relationship_data?feature=${selectedFeature}`)
               .then(response => response.json())
               .then(data => {
                    if (data.status === 'success') {
                        const chartContainer = document.getElementById('relationshipChartContainer');
                        chartContainer.innerHTML = data.chart_html;

                        // 手动触发 pyecharts 渲染
                        const scriptTags = chartContainer.getElementsByTagName('script');
                        for (let i = 0; i < scriptTags.length; i++) {
                            const script = document.createElement('script');
                            script.innerHTML = scriptTags[i].innerHTML;
                            document.body.appendChild(script);
                        }
                    } else {
                        console.error(data.message);
                    }
                })
               .catch(error => {
                    console.error('请求出错:', error);
                });
        });
        document.getElementById('featureSelect').addEventListener('change', function() {
        const selectedFeature = this.value;
        fetch(`/get_relationship_data?feature=${selectedFeature}`)
           .then(response => response.json())
           .then(data => {
                if (data.status === 'success') {
                    const chartContainer = document.getElementById('relationshipChartContainer');
                    chartContainer.innerHTML = data.chart_html;

                    // 手动触发 pyecharts 渲染
                    const scriptTags = chartContainer.getElementsByTagName('script');
                    for (let i = 0; i < scriptTags.length; i++) {
                        const script = document.createElement('script');
                        script.innerHTML = scriptTags[i].innerHTML;
                        document.body.appendChild(script);
                    }
                } else {
                    console.error(data.message);
                }
            })
           .catch(error => {
                console.error('请求出错:', error);
            });
    });
        document.getElementById('dataAnalysisTab').addEventListener('click', function() {
            window.location.href ="{{ url_for('data_analysis') }}";
            console.log('数据分析标签被点击');
        });

        document.getElementById('dataForecastTab').addEventListener('click', function() {
            window.location.href = "{{ url_for('data_yuce') }}";
            console.log('数据预测标签被点击');
        });

        document.getElementById('historyTab').addEventListener('click', function() {
             window.location.href = "{{ url_for('data_history') }}";
            console.log('历史记录标签被点击');
        });

        // 获取相关性数据
        fetch('/get_correlation_data')
           .then(response => response.json())
           .then(data => {
                if (data.status === 'success') {
                    // 填充基本统计表格
                    const stats = data.stats;
                    const statsTableBody = document.getElementById('stats-table-body');
                    for (const attribute in stats) {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${attribute}</td>
                            <td>${stats[attribute].max}</td>
                            <td>${stats[attribute].min}</td>
                            <td>${stats[attribute].mean}</td>
                            <td>${stats[attribute].std}</td>
                        `;
                        statsTableBody.appendChild(row);
                    }

                    // 插入热力图
                    const heatmapContainer = document.getElementById('heatmap-container');
                    heatmapContainer.innerHTML = data.heatmap;

                    // 手动触发 pyecharts 渲染
                    const scriptTags = heatmapContainer.getElementsByTagName('script');
                    for (let i = 0; i < scriptTags.length; i++) {
                        const script = document.createElement('script');
                        script.innerHTML = scriptTags[i].innerHTML;
                        document.body.appendChild(script);
                    }
                } else {
                    console.error(data.message);
                }
            })
           .catch(error => {
                console.error('请求出错:', error);
            });

        // 获取节假日负荷对比数据
        fetch('/get_load_comparison')
           .then(response => response.json())
           .then(data => {
                if (data.status === 'success') {
                    // 插入负荷对比图表
                    const loadContainer = document.getElementById('load-comparison-container');
                    loadContainer.innerHTML = data.chart_html;

                    // 手动触发 pyecharts 渲染
                    const scriptTags = loadContainer.getElementsByTagName('script');
                    for (let i = 0; i < scriptTags.length; i++) {
                        const script = document.createElement('script');
                        script.innerHTML = scriptTags[i].innerHTML;
                        document.body.appendChild(script);
                    }
                } else {
                    console.error(data.message);
                }
            })
           .catch(error => {
                console.error('请求出错:', error);
            });

        // 获取气象因素 对负荷影响的饼状图数据
        fetch('/get_weather_load_pie_chart')
           .then(response => response.json())
           .then(data => {
                if (data.status === 'success') {
                    // 插入饼状图
                    const pieChartContainer = document.getElementById('weather-load-pie-chart-container');
                    pieChartContainer.innerHTML = data.chart_html;

                    // 手动触发 pyecharts 渲染
                    const scriptTags = pieChartContainer.getElementsByTagName('script');
                    for (let i = 0; i < scriptTags.length; i++) {
                        const script = document.createElement('script');
                        script.innerHTML = scriptTags[i].innerHTML;
                        document.body.appendChild(script);
                    }
                } else {
                    console.error(data.message);
                }
            })
           .catch(error => {
                console.error('请求出错:', error);
            });

        fetch('/get_load_curve_data')
   .then(response => response.json())
   .then(data => {
        if (data.status === 'success') {
            const container = document.getElementById('loadCurveContainer');
            container.innerHTML = data.chart_html;

            // 手动触发 pyecharts 渲染
            const scriptTags = container.getElementsByTagName('script');
            for (let i = 0; i < scriptTags.length; i++) {
                const script = document.createElement('script');
                script.innerHTML = scriptTags[i].innerHTML;
                document.body.appendChild(script);
            }
        } else {
            console.error(data.message);
        }
    })
   .catch(error => {
        console.error('请求出错:', error);
    });
   </script>
</body>
<footer class="footer mt-auto py-3 bg-light">
    <div class="container text-center">
        <span class="text-muted">© 2025电力消费数据分析系统</span>
    </div>
</footer>
</html>